<!-- 入库订单 -->
<template>
  <div class="page-container">
    <page_breadcrumb :getKeyMethod="init_table_model" @change="change_table_model" pageOption />



    <ex_super_table_page v-bind="option" ref="SuperTablePage" @selection-change="li => selection = li"
      >

    </ex_super_table_page>
    <el-dialog :close-on-click-modal="false" :title="$tt('label_order_audit')" :visible.sync="dialogAudit"
      custom-class="dialog_small">

      <el-form :label-width="$globalCss.formLabelWidth_default" :model="auditForm" :rules="auditRules" ref="AuditForm">
        <el-form-item :label="$tt('text_has_select_order')">
          <ex_super_table v-bind="optionAudit" :data="dialogAuditItems" max-height="300" />
        </el-form-item>
        <el-form-item :label="$tt('label_audit_pass')" class="form_input_default" prop="isAdopt">
          <ex_super_input type="select" v-model="auditForm.isAdopt" enum="YesOrNoEnum" :clearable="false"
            class="widthdiv1" />
        </el-form-item>
        <el-form-item :label="$tt('label_audit_reject_reason')" v-if="auditForm.isAdopt == 'N'" prop="rejectReason">
          <ex_super_input v-model="auditForm.rejectReason" class="widthdiv1" :attrs="{ type: 'textarea' }" autosize
            :placeholder="$tt('label_audit_reject_reason')" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog_footer">
        <el-button @click="dialogAudit = false">{{ $tt('label_cancel') }}</el-button>
        <el-button type="primary" @click="submitAuditOrder">{{ $tt('label_submit') }}</el-button>
      </span>
    </el-dialog>

    <print_pre_box_generate ref="print_pre_box_generate" />
    <report_anomaly ref="report_anomaly" :orderTypeList="['INBOUND']" @afterSubmitSuccess="reload()" />
  </div>
</template>
<script>
import moment from 'moment-mini-ts'

import superTablePageFunction from '@/mixin/super-table-page-function';
import emitOnFunction from '@/mixin/emit-on-function';
import business_function from "@/common/business_function"

import page_table_model_manage from '@/mixin/page_table_model_manage';
import print_pre_box_generate from '@/component/print/print_pre_box_generate'
import report_anomaly from '@/component/dialog/report_anomaly.vue'

let emitKey = 'order=>manage'

export default {

  title: "title_inbound_order",
  mixins: [superTablePageFunction, emitOnFunction(emitKey), page_table_model_manage],
  components: { print_pre_box_generate, report_anomaly, },


  data() {
    return {
      selection: [],
      auditForm: {
        rejectReason: "",
        isAdopt: 'Y',
      },
      auditRules: {
        isAdopt: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'change' },
        rejectReason: [{ required: true, message: this.$tt('tip_can_no_empty'), trigger: 'change' }],
      },
      dialogAuditItems: [],
      dialogAudit: false,

      limitDate: null,
      option: {
        search: {
          formDataHandle: (data) => {
            const out = _.cloneDeep(data)
            if (out.daterange.length >= 2&&!out.receivingOrderCodes) {
              out.startCreateTime = out.daterange[0]
              out.endCreateTime = out.daterange[1]
            }
            return out
          },
          default: {
            daterange: [moment().set({ 'hours': 0, 'minutes': 0, 'seconds': 0, 'milliseconds': 0 }).subtract(3, 'months').valueOf(), moment().set({ 'hours': 23, 'minutes': 59, 'seconds': 59, 'milliseconds': 0 }).valueOf()]
          },
          model: [
            { label: "label_order_code", key: "receivingOrderCodes", placeholder: 'tip_input_can_comma_separated' },
            { label: "label_sku", key: "skuId", type: 'sku_selec_input' },
            // { label: "label_warehouse_name", key: "warehouseName", },
            {
              label: "label_transit_warehouse", key: "transitWarehouseId", type: 'base_warehouse_select', fold: false, isTransit: true,
            },
            // { label: "label_order_status", key: "customerStatus", type: 'select', enum: 'ReceivingCustomerStatusEnum', if: () => !this.$loginUser.ifElse澳越, },
            { label: "label_order_status", key: "status", type: 'select', enum: 'ReceivingOperationStatusEnum', },

            {
              label: "label_destination_warehouse", key: "destinationWarehouseId", type: 'base_warehouse_select', fold: false,
              isTransit: false,
            },
            { label: "label_inbound_type", key: "inboundType", type: 'select', enum: 'InboundTypeEnum', fold: true },
            { label: "label_delivery_type", key: "deliveryType", type: 'select', enum: 'DeliveryTypeEnum', fold: true },
            { label: 'label_business_type', key: 'bizType', type: 'select', enum: 'BizTypeEnum', fold: true, },
            { label: "label_is_insurance", key: "isInsurance", type: 'select', enum: 'YesOrNoEnum', fold: true },
            { label: 'label_customs_service', key: 'customsType', type: 'select', enum: 'CustomsTypeEnum', fold: true },

            {
              label: "label_time_range", key: "daterange", type: 'date-picker', fold: false,
              attrs: {
                clearable: false,
                type: 'datetimerange', 'default-time': ['00:00:00', '23:59:59'],
                'popper-class': "no_clear_range_picker",
                'picker-options': {
                  shortcuts: this.$date_range_shortcuts(),
                  onPick: (d) => {
                    this.limitDate = d.minDate
                  },
                  disabledDate: (t) => {
                    if (moment(t).isAfter(moment().set({ 'hours': 23, 'minutes': 59, 'seconds': 59, 'milliseconds': 999 }))) return true
                    if (this.limitDate != null) {
                      if (moment(t).isAfter(moment(this.limitDate).add(3, 'months')) ||
                        moment(t).isBefore(moment(this.limitDate).subtract(3, 'months'))) {
                        return true
                      }
                    }
                    return false
                  }
                },
              },
              on: {
                blur: () => { this.limitDate = null }
              }
            },
          ],
        },
        actionExtra: [
          {
            label: 'label_print_box_mark',
            click: () => this.printGenerate(),
          },
          { label: 'title_new_inbound_oder', attrs: { type: "primary" }, click: this.creatOrder },
        ],
        table: {
          url: "/oms-api/client/InboundReceivingClientRpc/selectPage.json",
          model: this.init_table_model(),
        }
        ,

      },
      optionAudit: {
        model: [
          { key: 'receivingOrderCode', label: 'label_order_code' },
          { key: 'customerName', label: 'label_customer_info' },
          {
            type: 'operate', width: 210, operate: [
              {
                label: "label_remove", class: 'button_text_danger',
                click: (row, i) => {
                  this.dialogAuditItems.splice(i, 1)
                  if (_.isEmpty(this.dialogAuditItems)) this.dialogAudit = false
                }
              },
            ]
          }
        ]
      },


    };
  },



  methods: {
    option_table_model() {
      return [
        { type: 'selection', clickToggle: true, keyGroup: 'label_table_operate' },
        { key: 'receivingOrderCode', label: 'label_order_code', 'min-width': 140, 'show-overflow-tooltip': true, },
        {
          key: 'inboundType',
          label: 'label_inbound_type',
          'width': 120,
          'show-overflow-tooltip': true,
          formatter: (r, c, v, i) => this.$enumShow(v, "InboundTypeEnum")
        },
        {
          key: 'transitWarehouseName',
          label: 'label_transit_warehouse',
          'min-width': 120,
          'show-overflow-tooltip': true,
          formatter: (r, c, v, i) => this.$formatNameCode(v, r.transitWarehouseCode)
        },
        {
          key: 'destinationWarehouseName',
          label: 'label_destination_warehouse',
          'min-width': 120,
          'show-overflow-tooltip': true,
          formatter: (r, c, v, i) => this.$formatNameCode(v, r.destinationWarehouseCode)
        },
        {
          key: 'isInsurance',
          label: 'label_insurance_server',
          'width': 120,
          'show-overflow-tooltip': true,
          formatter: (r, c, v, i) => this.$enumShow(v, "YesOrNoEnum")
        },
        { key: 'expectBoxQty', label: 'label_expected_box_number', 'width': 100, },
        { key: 'expectSkuQty', label: 'label_expected_sku_number', 'width': 100, },
        {
          label: 'label_business_type', key: 'bizType', 'width': 120, 'show-overflow-tooltip': true,
          formatter: (r, c, v, i) => this.$enumShow(v, "BizTypeEnum")
        },
        // {
        //   key: 'customerStatus', label: 'label_order_status', 'width': 120, 'show-overflow-tooltip': true,
        //   formatter: (r, c, v, i) => this.$enumShow(v, "ReceivingCustomerStatusEnum")
        // },
        {
          key: 'status', label: 'label_order_status', 'width': 120, 'show-overflow-tooltip': true,
          formatter: (r, c, v, i) => this.$enumShow(v, "ReceivingOperationStatusEnum")
        },

        { key: 'gmtCreate', label: 'label_create_order_date', formatter: (r, c, v, i) => this.$dateFormat(v) },

        { key: 'checkoutTime', label: 'label_transfer_checkout_date', formatter: (r, c, v, i) => this.$dateFormat(v) },
        { key: 'overseasPutawayTime', label: 'label_overseas_put_date', formatter: (r, c, v, i) => this.$dateFormat(v) },
        {
          key: 'errorMessage', label: 'label_error_info', width: 180,
          render: (h, { row, column }) => {
            const code = ['GET_TRACK_NUMBER_FAIL', 'PURCHASE_INSURANCE_FAIL'].includes(row.status) ? row.errorMessage : ''
            if (!code) return this.$tt('data_temp_none')
            return (<text_extra_tooltip_operate
              value={code} ellipsis
              data_type={column.property} data_id={row.id}
            />)
          },

        },
        {
          type: 'operate', width: 210, operate: [
            {
              label: "label_edit",
              if: this.isEditShow,
              disabled: this.isEditDisabled,
              click: (row) => {
                this.editOrder(row)
              }
            },
            {
              label: 'label_delete', type: "confirm-button", buttonClass: "button_text_danger", confirmButtonType: 'danger',
              if: this.isCanDelete,
              url: '/oms-api/client/InboundReceivingClientRpc/cancelReceiving.json', message: 'text_confirm_sure_delete',
              params: (v) => { return { receivingId: v.id } }, done: ['reload', 'tip']
            },

            {
              type: 'more',
              items: [
                { label: 'label_view_detail', click: (row) => this.clickDetail(row) },

                {
                  label: 'label_copy_new',
                  click: (row) => this.copyOrder(row),
                },

                { label: 'label_download_attachment', click: row => this.downloadAttachment(row) },
                {
                  label: 'label_report_exception', click: row => {
                    this['$refs']['report_anomaly'].showNew({
                      disabledEditInfo: true,
                      data: {
                        orderType: 'INBOUND',
                        orderNo: row.receivingOrderCode,
                      },
                      onlySetData: true,
                    })

                  }
                },
                {
                  label: "label_tms_waybill_check_track",
                  click: (row) => {
                    this.$router.push({ path: '/page/oms/track/track_list', query: { trackNumber: row.receivingOrderCode, } })
                  }
                },
                {
                  label: "label_cancel",
                  click: (row) => this.cancelOrder(row)
                },
              ]
            }
          ],
        },
      ]
    },

    isCanDelete(row) {
      return row.customerStatus == 'DRAFT'
    },
    isEditShow(row) {
      return row.isWarehouseEdit != 'Y'
    },
    isEditDisabled(row) {
      return row.isUpdatable != 'Y'||row.isPurchaseOrder==='Y'
      let _TRANSIT = row.inboundType == 'TRANSIT'
      let canEdit = false
      if (_TRANSIT) {
        canEdit = ['DRAFT', 'WAIT_AUDIT', 'AUDIT_REJECT', 'PURCHASE_INSURANCE_FAIL', 'GET_TRACK_NUMBER_FAIL'].some(e => e == row.status)
      } else {
        canEdit = ['DRAFT', 'WAIT_AUDIT', 'AUDIT_REJECT', 'PURCHASE_INSURANCE_FAIL', 'GET_TRACK_NUMBER_FAIL', 'TRANSIT_TRANSPORT',].some(e => e == row.status)
      }
      return !canEdit
    },
    clickDetail(row) {
      // let title = this.$tt('label_order_code') + row.receivingOrderCode
      // this.$refs['detail_order_inbound'].show({ params: { receivingId: row.id }, title })
      this.$router.push({
        path: '/page/oms/order/inbound/order_detail', query: { receivingId: row.id, }
      })
    },
    copyOrder(row,oriBox) {
      const query = { receivingId: row.id, copy: true, edit: true, emitKey }
      this.$router.push({ path: '/page/oms/order/inbound/order_operate', query, })
    },
    editOrder(row) {
      this.$router.push({
        path: '/page/oms/order/inbound/order_operate', query: { receivingId: row.id, edit: true, emitKey }
      })
    },
    creatOrder() {
      this.$router.push({ path: '/page/oms/order/inbound/order_operate', query: { emitKey, } })


    },
    clickAuditList() {
      let _list = this.selection
      if (_.isEmpty(_list)) {
        return this.$message.error(this.$tt('tip_please_select_order'))
      }
      this.dialogAuditItems = _.cloneDeep(_list)
      this.dialogAudit = true
    },
    submitAuditOrder() {
      this.$refs['AuditForm'].validate((valid) => {
        if (valid) {
          this.auditOrder()
        } else {
          this.$message.error(this.$tt('form_validate_error'))
          return false;
        }
      })
    },
    downloadAttachment(row) {
      if (row.attachment_list) {
        this.showOrderAttachmentBox(row)
        return
      }
      this.$ajax({
        url: this.$url['oms/downloadInboundAttachment'],
        method: 'post',
        loading: true,
        data: {
          receivingId: row.id,
        },
        success: (res) => {
          if (res.data && res.data.rows) {
            row.attachment_list = res.data.rows
            this.showOrderAttachmentBox(row)
          }
        },
      })
    },
    showOrderAttachmentBox(row) {
      const h = this.$createElement;
      this.$msgbox({
        title: this.$tt('label_attachment_download'),
        message: h('div', null,
          row.attachment_list.map(it => {
            return h('div', { class: 'mg_v1' }, [
              h('a', {
                class: 'a_file_link',
                attrs: {
                  href: this.$ex_default_download_url + it.filePath,
                  target: '_blank',
                  download: it.fileName,
                }
              }, [h('i', { class: 'el-icon-download el-icon--left' }), it.fileName])
            ])
          })),
        // showCancelButton: true,
        showConfirmButton: false,
      }).then(action => {

      });
    },
    auditOrder() {
      let data = _.clone(this.auditForm)
      data.receivingIdList = this.dialogAuditItems.map(it => it.id)
      let isNeedReloadTransfer = this.dialogAuditItems.some(it => it.inboundType == 'TRANSIT')
      let isNeedReloadDirect = this.dialogAuditItems.some(it => it.inboundType == 'DIRECT')
      this.$ajax({
        url: "/oms-api/client/InboundReceivingClientRpc/audit.json",
        method: 'post', type: 'json',
        loading: this.$tt('tip_submiting'),
        data,
        success: (res) => {
          this.dialogAudit = false
          this.reload()
          this.$message.success(this.$tt('tip_submit_success'))
          if (isNeedReloadTransfer) this.$emitPage('transfer=>receiving_list', 'reload')
          if (isNeedReloadDirect) this.$emitPage('standard>inbound_manage', 'reload')
        }
      })
    },
    printGenerate() {
      this.$refs.print_pre_box_generate.show({})
    },

    cancelOrder(row) {
      this.$confirm(this.$tt('tip_confirm_cancel_select_order_any_cancel_no_replay', { any: row.receivingOrderCode }), this.$tt('label_tip'), {
        type: 'warning'
      }).then(() => {
        this.$ajax({
          url: this.$url['oms/inboundOrder/cancelOrder'],
          method: 'post',
          loading: true,
          data: {
            id: row.id
          },
          success: (res) => {
            this.$message({
              showClose: true,
              message: this.$tt('tip_submit_success'),
              type: 'success'
            })
            this.reload()
          }
        })
      }).catch(() => {
      });
    },
  }
};

</script>
<style></style>
